package com.ydm.myapp001.activity;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ydm.myapp001.R;
import com.ydm.myapp001.dialog.GoodsDetailDialog;
import com.ydm.myapp001.service.DownloadService;
import com.ydm.myapp001.utils.AidlUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "YDMLog_MainActivity"; //输logt会自动补全
    private Button btn1;
    private Button btn2;
    private Button btn_second001;
    private Button btn_second002;
    private Button btn_second003;
    private Button btn_second004;
    private Button btnGoogle;
    private Button btnGaode;
    private Button btnFilecreate;
    private ImageButton imgBtn;
    private TextView textView;
    private PopupWindow popupWindow;
    private View contentView;
    private Context mContext;
    String[] single_list = {"男","女","女博士","程序员"};
    String[] multi_list = {"篮球","足球","游泳","武术"};
    String[] item_list = {"项目经理","策划","测试员","美工","程序工程师"};
    NotificationManager notiManager;
    int notification_ID;

    //
    MediaPlayer mp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: MainActivity");
        setContentView(R.layout.activity_main);

        notiManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mContext = this;

        /*
         * 通过点击btn1实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */
        btn1 = (Button) findViewById(R.id.button1_first);
        //注册点击事件
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
                Intent intent = new Intent(mContext, SecondActivity.class);
                startActivity(intent);
                System.out.println("第一种方式-匿名内部类实现监听");
            }
        });


        /*
         * 通过点击btn2实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */

        btn2 = (Button) findViewById(R.id.button2_second);
        //注册点击事件
        btn2.setOnClickListener(listener);



        textView = (TextView) findViewById(R.id.textView1);



        /*
         * 通过点击btn_second001实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */
        btn_second001 = (Button) findViewById(R.id.button_second001);
        //注册点击事件
        btn_second001.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
                Intent intent = new Intent(mContext, Second001Activity.class);
                startActivity(intent);
                Log.d(TAG, "onClick: 跳转到Second001Activity");
            }
        });



        /*
         * 通过点击btn_second002实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */
        btn_second002 = (Button) findViewById(R.id.button_second002);
        //注册点击事件
        btn_second002.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
                Intent intent = new Intent(mContext, Second002Activity.class);
                startActivity(intent);
                Log.d(TAG, "onClick: 跳转到Second002Activity");
            }
        });



        /*
         * 通过点击btn_second003实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */
        btn_second003 = (Button) findViewById(R.id.button_second003);
        //注册点击事件
        btn_second003.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
                Intent intent = new Intent(mContext, Second003Activity.class);
                startActivity(intent);
                Log.d(TAG, "onClick: 跳转到Second003Activity");
            }
        });



        /*
         * 通过点击btn_second004实现页面之间的跳转
         * 1. startActivity的方式来实现
         * ①初始化Intent
         */
        btn_second004 = (Button) findViewById(R.id.button_second004);
        //注册点击事件
        btn_second004.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
                Intent intent = new Intent(mContext, Second004Activity.class);
                startActivity(intent);
                Log.d(TAG, "onClick: 跳转到Second004Activity");
            }
        });



        /*
         *  通过接口的方式实现监听 --- 展示一个Toast
         */
        imgBtn = (ImageButton) findViewById(R.id.imageButton);
        imgBtn.setOnClickListener(this);



        //发送通知按钮
        findViewById(R.id.btn_send).setOnClickListener(this);
        //取消通知按钮
        findViewById(R.id.btn_cancel).setOnClickListener(this);




        //ping谷歌
        btnGoogle = (Button) findViewById(R.id.btn_pinggoogle);
        //注册点击事件
        btnGoogle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: ping谷歌");
                Boolean res = ping("www.google.com");
                if (res) {
                    Log.d(TAG, "ping谷歌通了");
                    Toast.makeText(mContext, "ping 谷歌 通了", LENGTH_SHORT);
                }
                else {
                    Log.d(TAG, "没ping通谷歌");
                    Toast.makeText(mContext, "ping 谷歌 不通", LENGTH_SHORT);
                }
            }
        });


        //ping高德
        btnGaode = (Button) findViewById(R.id.btn_pinggaode);
        //注册点击事件
        btnGaode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: ping高德");
                Boolean res = ping("www.gaode.com");
                if (res) {
                    Log.d(TAG, "ping通高德了");
                    Toast.makeText(mContext, "ping 高德 通了", LENGTH_SHORT);
                }
                else {
                    Log.d(TAG, "没ping通高德");
                    Toast.makeText(mContext, "ping 高德 不通", LENGTH_SHORT);
                }
            }
        });



        //文件创建按钮
        btnFilecreate = (Button) findViewById(R.id.btn_filecreate);
        //注册点击事件
        btnFilecreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: 文件创建");
                File file = new File("/mnt/sdcard/ydmtest");
                if (!file.exists()){
                    try {
                        file.createNewFile();
                    }
                    catch (IOException e){
                        e.printStackTrace();
                    }
                }
                else {
                    Toast.makeText(mContext, "文件已经存在", LENGTH_SHORT);
                }


                //
                File file1 = getFilesDir();//这个目录是当前应用程序默认的数据存储目录
                Log.d(TAG, "onClick: "+ file1.toString());//打印结果：/data/data/com.ydm.myapp001/files

                File file2 = getCacheDir();//这个目录是当前应用程序默认的缓存文件的存放目录
                Log.d(TAG, "onClick: "+ file2.toString());//打印结果：/data/data/com.ydm.myapp001/cache

                File file3 = getDir("myselfdir", MODE_PRIVATE);
                Log.d(TAG, "onClick: "+ file3.toString());//打印结果：/data/data/com.ydm.myapp001/app_myselfdir

                File file11 = getExternalCacheDir();
                Log.d(TAG, "onClick: "+ file11.toString());
            }
        });

        //
        test001();



        //
        AidlUtil.getInstance().connectPrinterService(this);
        AidlUtil.getInstance().initPrinter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: MainActivity");
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.i("tag", "第二种方式-独立外部类实现监听");
            /*
                 * 第一个参数：上下文对象this
                 * 第二个对象
                 */
            Intent intent = new Intent(mContext, SecondActivity.class);
            startActivityForResult(intent, 1);
        }
    };


    @Override
    public void onClick(View view) {
        Log.i(TAG, "第三种方式-通过接口的方式实现监听");
        switch (view.getId()) {
            case R.id.button_second001: {

            }
            case R.id.imageButton: {
                //showToast();
                //showAlertDialog1();
                //showAlertDialog2();
                //showAlertDialog3();
                //showAlertDialog4();
                showAlertDialog5();
            }
                break;
            case R.id.btn_send:
                sendNotification();
                break;
            case R.id.btn_cancel:
                notiManager.cancel(notification_ID);
                break;
        }
    }

    private void playRing(String filename) {
        try {
            //设置为最大音量
            AudioManager audioMa = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            audioMa.setStreamVolume(AudioManager.STREAM_MUSIC, audioMa.getStreamMaxVolume
                    (AudioManager.STREAM_MUSIC), AudioManager.AUDIOFOCUS_NONE);
            //获取mp3资源并播放
            AssetManager am = getAssets();
            AssetFileDescriptor afd = am.openFd(filename);
            mp = new MediaPlayer();
            mp.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            mp.setLooping(false);//循环播放
            mp.prepare();
            mp.start();
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {

                    /*
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {

                        }
                    }, 2000);
                    */
                }
            });
        } catch (IOException e) {

        }
    }

    //播放扫码成功的提示音
    private void playScanSuccAuido() {
        //播放扫码失败的提示音 -- 防止重音播放，需要判断一下
        if (mp!=null && mp.isPlaying()) {
            mp.stop();
        }

        playRing("scan_success.mp3");
    }

    //播放扫码失败的提示音
    private void playScanFailAuido() {
        //播放扫码失败的提示音 -- 防止重音播放，需要判断一下
        if (mp!=null && mp.isPlaying()) {
            mp.stop();
        }

        playRing("scan_fail.mp3");
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(TAG, "requestCode:"+requestCode+"；resultCode="+resultCode);
        if (requestCode==1 && resultCode==11) {
            String res = data.getStringExtra("key1");
            textView.setText(res);
        }
    }



    public void test001(){
        Log.v(TAG, "test001: Log.v");
        Log.d(TAG, "test001: Log.d");
        Log.i(TAG, "test001: Log.i");
        Log.w(TAG, "test001: Log.w");
        Log.e(TAG, "test001: Log.e");
    }


    /*
    * 展示一个Toast
    * */
    public void showToast(){
        LayoutInflater inflater = LayoutInflater.from(this);
        View toast_view = inflater.inflate(R.layout.toast_layout, null);
        Toast toast = new Toast(this);
        toast.setView(toast_view);
        toast.show();
    }


    /*
    * 显示确认对话框
    * */
    public void showAlertDialog1(){
        //创建一个AlertDialog对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setIcon(R.drawable.default_avatar);
        dialogBuilder.setTitle("温馨提示");
        dialogBuilder.setMessage("确定要继续吗？");
        //dialogBuilder.setCancelable(true);
        //定义确定按钮以及点击事件
        dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d(TAG, "点击了确定按钮");
            }
        });
        //定义"取消"按钮以及点击事件
        dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d(TAG, "点击了取消按钮");
            }
        });
        //创建对话框
        AlertDialog alertDialog = dialogBuilder.create();
        //展示对话框
        alertDialog.show();
    }



    /*
    * 显示单选按钮对话框
    * */
    public void showAlertDialog2(){
        //创建一个AlertDialog对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setIcon(R.drawable.default_avatar);
        dialogBuilder.setTitle("选择性别");
        dialogBuilder.setSingleChoiceItems(single_list, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d(TAG, "onClick: " + single_list[i]);
            }
        });

        //创建对话框
        AlertDialog alertDialog = dialogBuilder.create();
        //展示对话框
        alertDialog.show();
    }



    /*
    * 显示多选按钮对话框
    * */
    public void showAlertDialog3(){
        //创建一个AlertDialog对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setIcon(R.drawable.default_avatar);
        dialogBuilder.setTitle("您的爱好是？");
        dialogBuilder.setMultiChoiceItems(multi_list, null, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                if (b) {
                    Log.d(TAG, "你选择了爱好： " + multi_list[i]);
                }
                else {
                    Log.d(TAG, "你未选择了爱好： " + multi_list[i]);
                }
            }
        });
        dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d("YDMTAG", "点击了确定按钮-选择完成");
            }
        });

        //创建对话框
        AlertDialog alertDialog = dialogBuilder.create();
        //展示对话框
        alertDialog.show();
    }


    /*
    * 显示列表对话框
    * */
    public void showAlertDialog4(){
        //创建一个AlertDialog对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setIcon(R.drawable.default_avatar);
        dialogBuilder.setTitle("部门列表");
        dialogBuilder.setItems(item_list, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d(TAG, "你选择了： " + item_list[i]);
            }
        });

        //创建对话框
        AlertDialog alertDialog = dialogBuilder.create();
        //展示对话框
        alertDialog.show();
    }


    /*
    * 自定义对话框
    * */
    public void showAlertDialog5(){
        //创建一个AlertDialog对话框
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setIcon(R.drawable.default_avatar);
        dialogBuilder.setTitle("部门列表");
        dialogBuilder.setItems(item_list, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.d(TAG, "你选择了： " + item_list[i]);
            }
        });

        //创建对话框
        AlertDialog alertDialog = dialogBuilder.create();
        //展示对话框
        alertDialog.show();
    }



    /*
    * 构造notification并发送到通知栏
    * */
    private void sendNotification(){
        Log.d(TAG, "sendNotification: ");
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, 0);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.default_avatar);//设置图标
        builder.setTicker("你好");//手机状态栏提示
        builder.setWhen(System.currentTimeMillis());//设置发出通知的时间
        builder.setContentTitle("通知栏标题");
        builder.setContentText("我是通知内容，哈哈哈哈哈哈，大笑对对对放声大哭东风快递");
        builder.setContentIntent(pintent);//点击以后的意图
        builder.setDefaults(Notification.DEFAULT_ALL);//设置提示声音、指示灯、震动
        Notification notification = builder.build();
        notiManager.notify(notification_ID, notification);
    }



    private static final boolean ping(String hostAddress) {

        String result = null;

        try {

            Process p = Runtime.getRuntime().exec("ping -c 1 -w 2 " + hostAddress);//ping3次


            // 读取ping的内容，可不加。

            InputStream input = p.getInputStream();

            BufferedReader in = new BufferedReader(new InputStreamReader(input));

            StringBuffer stringBuffer = new StringBuffer();

            String content = "";

            while ((content = in.readLine()) != null) {

                stringBuffer.append(content);

            }

            Log.i(TAG, "result content : " + stringBuffer.toString());


            // PING的状态

            int status = p.waitFor();

            if (status == 0) {

                result = "successful~";

                return true;

            } else {

                result = "failed~ cannot reach the IP address";

            }

        } catch (IOException e) {

            result = "failed~ IOException";

        } catch (InterruptedException e) {

            result = "failed~ InterruptedException";

        } finally {

            Log.i(TAG, "result = " + result);

        }

        return false;

    }






    /**
     * 按钮的监听
     * @param v
     */
    public void openPopWindow(View v) {
        Log.d(TAG, "openPopWindow: ");
        if (popupWindow == null) {
            creatPopWindow();
        }

        backgroundAlpha(0.6f);//半透明背景
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    public void creatPopWindow(){
        contentView = LayoutInflater.from(mContext).inflate(R.layout.popwindow, null);
        //设置弹出框的宽度和高度
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //取得焦点
        popupWindow.setFocusable(true);
        //注意 要是点击外部空白处弹框消失 那么必须给弹框该设置一个背景色 不然是不会起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        //弹出的popWin关闭的事件的监听，主要是为了将背景透明度改回来
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //值为0.0 - 1.0
        getWindow().setAttributes(lp);
    }
    
    
    
    
    
    public void jumpToWebViewPage(View v) {
        Log.d(TAG, "jumpToWebViewPage: ");
        Intent intent = new Intent(mContext, WebViewActivity.class);
        startActivity(intent);
    }


    public void jumpToBaiduMap(View v) {
        Log.d(TAG, "jumpToBaiduMap: ");
        Intent intent = new Intent(mContext, BaiduMapActivity.class);
        startActivityForResult(intent, 10002);
    }


    public void sendYdmBroadcast(View v) {
        Log.d(TAG, "sendYdmBroadcast: ");
        Intent intent = new Intent("android.intent.action.MY_BROADCAST");
        intent.putExtra("msg", "通知，我是杨冬明0458pm");
        sendOrderedBroadcast(intent, "harvic.broadcast.permission");
    }


    public void goToDialogActivity (View v) {
        Log.d(TAG, "goToDialogActivity: ");
        Intent intent = new Intent(mContext, DialogActivity.class);
        startActivity(intent);
        Log.d(TAG, "onClick: 跳转到DialogActivity");
    }


    public void printSummiTicket (View v) {
        Log.d(TAG, "printSummiTicket: ");
        //已经在oncreate中连接打印机服务和初始化打印机了


        //打印
        AidlUtil.getInstance().printText();
    }

    public void goToBindServiceActivity (View v) {
        Log.d(TAG, "goToBindServiceActivity: ");
        Intent intent = new Intent(mContext, BindServiceActivity.class);
        startActivity(intent);
    }

    public void goToStartServiceActivity (View v) {
        Log.d(TAG, "goToStartServiceActivity: ");
        Intent intent = new Intent(mContext, StartServiceActivity.class);
        startActivity(intent);
    }

    public void goToMixServiceActivity (View v) {
        Log.d(TAG, "goToMixServiceActivity: ");
        Intent intent = new Intent(mContext, MixServiceActivity.class);
        startActivity(intent);
    }

    public void goToBCR001Activity(View v) {
        Log.d(TAG, "goToBCR001Activity: ");
        Intent intent = new Intent(mContext, DynamicBCR001Activity.class);
        startActivity(intent);
    }

    public void downloadApkAndInstall(View v) {
        Intent intent = new Intent(mContext, DownloadService.class);
        startService(intent);
    }

    public void goToSystemCommonServiceActivity(View v) {
        Intent intent = new Intent(mContext, SystemCommonServiceActivity.class);
        startActivity(intent);
    }

    public void goToRecyclerView001(View v) {
        Intent intent = new Intent(mContext, RecyclerView001Activity.class);
        startActivity(intent);
    }

    public void showDialogFramet(View v) {
        final GoodsDetailDialog detailDialog = new GoodsDetailDialog();
        //显示
        detailDialog.show(getSupportFragmentManager(), "detailDialog");
    }

    public void goToTestHttp(View v) {
        Intent intent = new Intent(mContext, TestHttpActivity.class);
        startActivity(intent);
    }

    public void playYuYin1(View v) {
        playScanSuccAuido();
    }

    public void playYuYin2(View v) {
        playScanFailAuido();
    }

    public void fenzuRecycle(View v) {
        Intent intent = new Intent(mContext, FenZuRecylceViewActivity.class);
        startActivity(intent);
    }
}
